import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login/index.vue'
import { useUserStore } from '@/stores'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({
  showSpinner: false
})

const router = createRouter({
  //import.meta.env.BASE_URL
  history: createWebHistory(),//createWebHistory() 参数默认是/
  routes: [
    {
      path:'/login',
      name:'login',
      meta:{title:'登录'},
      component:Login
    },
    {
      path:'/',
      name:'layout',
      component:()=>import('@/views/Layout/index.vue'),
      children:[
        {
        path:'/home',
        meta:{title:'首页'},
        component:()=>import("@/views/Home/index.vue")
        },
        {
        path:'/article',
        meta:{title:'健康百科'},
        component:()=>import("@/views/Article/index.vue")
        },
        {
        path:'/notify',
        meta:{title:'消息中心'},
        component:()=>import("@/views/Notify/index.vue")
        },
        {
        path:'/user',
        meta:{title:'我的',},
        component:()=>import("@/views/User/index.vue")
        },
        {
          path:'/user/patient',
          component: () => import('@/views/User/patientPage.vue'),
          meta: { title: '家庭档案' }
        },
        {
          path: '/consult/fast',
          component: () => import('@/views/Consult/ConsultFast.vue'),
          meta: { title: '极速问诊' }
        },
        {
          path: '/consult/dep',
          component: () => import('@/views/Consult/ConsultDep.vue'),
          meta: { title: '选择科室' }
        },
        {
          path: '/consult/illness',
          component: () => import('@/views/Consult/ConsultIllness.vue'),
          meta: { title: '病情描述' }
        },
        {
          path: '/consult/pay',
          component: () => import('@/views/Consult/ConsultPay.vue'),
          meta: { title: '问诊支付' }
        },
        // {
        //   path: '/room',
        //   component: () => import('@/views/Room/index.vue'),
        //   meta: { title: '问诊室' },
        //   beforeEnter(to) {
        //     if (to.query.payResult === 'false') return '/user/consult'
        //   }
        // },
    
    
    
    
    
      ]
    }
  ]
})

// vue2的导航守卫
// router.beforeEach((to,from,next)=>{

// })

// vue3的导航守卫：
//  to:是要访问的页面
//   如果没有权限（没有token），只要return'/login'：表示返回到登录页面
//   如果有token的话什么也不做，表示放行
router.beforeEach((to)=>{
  NProgress.start()
  // 从pinia查询token 如果没有token并且访问的页面不是白名单中的页面那么就跳转到login页面
 const store = useUserStore()
 const whiteList=['/login','/register','/login/callback']

//  console.log(store.user?.token)
 
 if (!store.user?.token && !whiteList.includes(to.path)) return '/login'
})


router.afterEach((to) => {
  document.title = `${to.meta.title || ''}-优医问诊`
  NProgress.done()
});
  
export default router
